package com.yenlien.traceyun.control.service;

import com.yenlien.traceyun.control.dao.CropDao;
import com.yenlien.traceyun.control.entity.Crop;
import com.yenlien.traceyun.control.service.rest.FileRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LiuSha on 2020/8/7.
 */
@Service
public class CropService {
    @Autowired
    private CropDao cropDao;
    @Autowired
    private FileRestService fileRestService;

    @Transactional(rollbackFor = RuntimeException.class)
    public void saves(List<Crop> cropList, String modelId, List<MultipartFile> files) throws Exception {
        List<Crop> births = findByModelId(modelId);
        List<String> deleteIds = new ArrayList<>();
        if (births.size() > 0) {
            deleteIds = births.stream().map(p -> p.getId()).collect(Collectors.toList());
        }
        for (Crop crop : cropList) {
            if (StringUtils.isEmpty(crop.getId())) {
                fileRestService.upload(null, crop, files);
            } else {
                fileRestService.upload(cropDao.findById(crop.getId()), crop, files);
            }
            crop.setModelId(modelId);
            cropDao.save(crop);
            if (deleteIds.size() > 0 && deleteIds.contains(crop.getId())) {
                deleteIds.remove(crop.getId());
            }
        }
        deletes(deleteIds);
    }

    public List<Crop> findByModelId(String modelId) {
        return cropDao.findByModelId(modelId);
    }

    public void deleteByModel(String modelId) {
        List<Crop> crops = cropDao.findByModelId(modelId);
        if (crops != null && crops.size() > 0) {
            cropDao.deleteInBatch(crops);
        }
    }

    public void deletes(List<String> ids) {
        for (String id : ids) {
            Crop crop = cropDao.findById(id);
            if (!StringUtils.isEmpty(crop.getImg())) {
                fileRestService.delete(crop.getImg());
            }
            cropDao.delete(crop);
        }
    }

}
